package com.hujinwen.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hujinwen.service.ESService;
import com.hujinwen.utils.JsonUtils;
import com.hujinwen.utils.server.ESClient;
import org.apache.http.HttpHost;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 * Created by joe on 2020/3/16
 */
@Service
public class ESServiceImpl implements ESService {

    private static final ESClient esClient = new ESClient(new HttpHost("192.168.192.134", 9200));

    @PreDestroy
    private void destroy() throws IOException {
        esClient.close();
    }

    @Override
    public String queryNote(String kw) throws IOException {
        return esClient.matchQuery("content", kw, "insert_test_index");
    }

    @Override
    public String putNote(String title, String tags, String content) throws JsonProcessingException {
        final ObjectNode dataNode = JsonUtils.newObjectNode();
        dataNode.put("title", title);
        dataNode.put("tags", tags);
        dataNode.put("content", content);

        esClient.postData("insert_test_index", JsonUtils.toString(dataNode));
        return "success";
    }
}
